<?php
namespace App\Common\Cla\Rbac\User\Relation;

use App\Common as com;
use App\Common\Cla\Rbac\User\Relation\Sava as nameSava;
use App\Common\Cla\Rbac\User\Relation as nameRelation;

class Sava extends com\Cla\ClaBase {

	/**
	 * 待保存的DataManager
	 * @return com\Model\RbacUserRelation\DataManager
	 */
	public function goWaitSaveDataManager(  ):com\Model\RbacUserRelation\DataManager {
		return $this->goPool( __METHOD__, function(){
			return com\Model\RbacUserRelation::dataManager();
		} );
	}

	/**
	 * 检查唯一性是否重复
	 * @return string|null [string]重复，并返回错误提示 [null]不重复
	 */
	private function checkRepeatUniqueReStr(  ):string|null {
		if( $this->goWaitSaveDataManager()->isCreate() ){
			$isExist = $this->goWaitSaveDataManager()->newSelf()
				->whereData_UserType( $this->goWaitSaveDataManager()->newData_UserType()->getSetData() )
				->whereData_UserId( $this->goWaitSaveDataManager()->newData_UserId()->getSetData() )
				->whereData_RbacType( $this->goWaitSaveDataManager()->newData_RbacType()->getSetData() )
				->isExist();
			if( $isExist ){
				return '数据已存在，不可重复创建';
			}
		}
		//
		return null;
	}

	/**
	 * 创建并返回数据id
	 * @return int 数据id
	 * @throws
	 */
	public function saveOfCreateReMainId():int {
		// 检查是否存在
		$repeatStr = $this->checkRepeatUniqueReStr();
		if( $repeatStr !== null ){
			throw com\Lib\Err\Exception::makeOfNew( $repeatStr, com\Lib\Err\Code::$sysSqlDataExist );
		}
		//
		return $this->goWaitSaveDataManager()->saveAllReMainId();
	}

	/**
	 * 创建并返回数据对象
	 * @return nameRelation\OfId 数据对象
	 * @throws
	 */
	public function saveOfCreateReOfIdObj():nameRelation\OfId {
		return nameRelation\OfId::makeOfIdOrObj( $this->saveOfCreateReMainId() );
	}

	/**
	 * 更新
	 * @return bool
	 */
	public function saveOfUpdate(  ):bool {
		$this->goWaitSaveDataManager()->saveOfUpdate();
		return true;
	}

	// ===============================
	//
	//
	// 下面为静态方法
	//
	//
	// ===============================

	/**
	 * @param int $userType
	 * @param int $userId
	 * @param int $rbacType
	 * @return $this
	 */
	public static function makeOfCreate( int $userType, int $userId, int $rbacType ):self {
		$saver = self::make();
		$saver->goWaitSaveDataManager()
			->setData_UserType( $userType )
			->setData_UserId( $userId )
			->setData_RbacType( $rbacType );
		//
		return $saver;
	}

	/**
	 * @param int $id
	 * @return $this
	 */
	public static function makeOfUpdate( int $id ):self {
		$saver = self::make();
		$saver->goWaitSaveDataManager()
			->whereData_Id( $id );
		return $saver;
	}

}
